package com.gewu.pm.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.bean.FunctionItemBean;
import com.gewu.pm.bean.FunctionModuleBean;
import com.gewu.pm.other.IntentKey;
import com.gewu.pm.ui.activity.clockin.ClockInManageActivity;
import com.gewu.pm.ui.activity.customer.DeliveryProviderActivity;
import com.gewu.pm.ui.activity.customer.SalesPersonActivity;
import com.gewu.pm.ui.activity.delivery.DeliveryManagementOrderActivity;
import com.gewu.pm.ui.activity.delivery.DeliveryManagementTerminalActivity;
import com.gewu.pm.ui.activity.delivery.DeliveryProviderReconciliationActivity;
import com.gewu.pm.ui.activity.funds.FreezerManagementActivity;
import com.gewu.pm.ui.activity.funds.GoldBeanManagementActivity;
import com.gewu.pm.ui.activity.order.PaymentReceiptActivity;
import com.gewu.pm.ui.activity.order.PendingPaymentActivity;
import com.gewu.pm.ui.activity.order.SalesOrderActivity;
import com.gewu.pm.ui.activity.order.TelegraphicTransferActivity;
import com.gewu.pm.ui.activity.payment.PaymentTermActivity;
import com.gewu.pm.ui.activity.promotion.PromotionManagementActivity;
import com.gewu.pm.ui.activity.report.DailyReportActivity;
import com.gewu.pm.ui.activity.sales.SalesLeadsActivity;
import com.gewu.pm.ui.activity.terminal.TerminalManagementActivity;
import com.gewu.pm.ui.activity.work.PromotionVisitActivity;
import com.gewu.pm.ui.activity.work.VisitManagementActivity;
import com.gewu.pm.ui.adapter.CommonFunctionAdapter;
import com.gewu.pm.ui.adapter.FunctionModuleAdapter;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventBusUtil;
import com.gewu.pm.utils.eventbus.EventCode;
import com.gewu.pm.widget.BottomButton;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 设置常用功能页面
 */
public final class CommonFunctionSettingActivity extends AppActivity {

    /** 最多添加的常用功能数量 */
    private static final int MAX_COMMON_FUNCTION_COUNT = 11;
    
    /** 页面模式：编辑模式 */
    public static final String MODE_EDIT = "mode_edit";
    /** 页面模式：查看模式（全部功能） */
    public static final String MODE_VIEW_ALL = "mode_view_all";

    private TextView tvCommonHint;
    private LinearLayout llCommonFunctionLayout;
    private View viewDivider;
    private RecyclerView rvCommonFunctions;
    private RecyclerView rvFunctionModuleBeans;
    private BottomButton btnConfirm;

    private CommonFunctionAdapter commonAdapter;
    private FunctionModuleAdapter moduleAdapter;

    /** 常用功能列表 */
    private List<FunctionItemBean> commonFunctionList = new ArrayList<>();
    /** 功能模块列表 */
    private List<FunctionModuleBean> functionModuleList = new ArrayList<>();
    
    /** 当前页面模式 */
    private String currentMode = MODE_EDIT;

    /**
     * 如果没携带参数，默认是(查看全部功能模式)
     */
    public static void start(Context context) {
        Intent intent = new Intent(context, CommonFunctionSettingActivity.class);
        intent.putExtra(IntentKey.TYPE, MODE_VIEW_ALL);//（全部功能）
        context.startActivity(intent);
    }

    /**
     * 启动并传递已选择的常用功能列表和页面模式（编辑模式） 页面模式：MODE_EDIT(编辑模式) 或 MODE_VIEW_ALL(查看全部功能模式)
     * @param context 上下文
     * @param selectedFunctions 已选择的常用功能
     */
    public static void start(Context context, List<FunctionItemBean> selectedFunctions) {
        Intent intent = new Intent(context, CommonFunctionSettingActivity.class);
        intent.putExtra(IntentKey.DATA_LIST, (Serializable) selectedFunctions);
        intent.putExtra(IntentKey.TYPE, MODE_EDIT);//编辑模式
        context.startActivity(intent);
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.common_function_setting_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvCommonHint = findViewById(R.id.tv_common_hint);
        llCommonFunctionLayout = findViewById(R.id.ll_common_function_layout);
        viewDivider = findViewById(R.id.view_divider);
        rvCommonFunctions = findViewById(R.id.rv_common_functions);
        rvFunctionModuleBeans = findViewById(R.id.rv_function_modules);
        btnConfirm = findViewById(R.id.btn_confirm);

        // 获取页面模式
        currentMode = getString(IntentKey.TYPE);
        
        // 根据模式设置标题
        if (MODE_VIEW_ALL.equals(currentMode)) {
            setTitle("全部功能");
        } else {
            setTitle("设置常用功能");
        }

        setOnClickListener(R.id.tv_bottom_button);

        // 设置常用功能RecyclerView
        GridLayoutManager commonLayoutManager = new GridLayoutManager(this, 4);
        rvCommonFunctions.setLayoutManager(commonLayoutManager);
        commonAdapter = new CommonFunctionAdapter(this);
        rvCommonFunctions.setAdapter(commonAdapter);

        // 只在编辑模式下启用拖动排序功能
        if (MODE_EDIT.equals(currentMode)) {
            ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
                @Override
                public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                    int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    return makeMovementFlags(dragFlags, 0);
                }

                @Override
                public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder,
                                      @NonNull RecyclerView.ViewHolder target) {
                    int fromPosition = viewHolder.getAdapterPosition();
                    int toPosition = target.getAdapterPosition();
                    Collections.swap(commonFunctionList, fromPosition, toPosition);
                    commonAdapter.notifyItemMoved(fromPosition, toPosition);
                    return true;
                }

                @Override
                public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                    // 不需要滑动删除功能
                }

                @Override
                public boolean isLongPressDragEnabled() {
                    return true; // 启用长按拖动
                }
            });
            itemTouchHelper.attachToRecyclerView(rvCommonFunctions);
        }

        // 设置功能模块RecyclerView
        LinearLayoutManager moduleLayoutManager = new LinearLayoutManager(this);
        rvFunctionModuleBeans.setLayoutManager(moduleLayoutManager);
        moduleAdapter = new FunctionModuleAdapter(this);
        rvFunctionModuleBeans.setAdapter(moduleAdapter);

        // 设置适配器的编辑模式
        boolean isEditMode = MODE_EDIT.equals(currentMode);
        commonAdapter.setEditMode(isEditMode);
        moduleAdapter.setEditMode(isEditMode);
        
        // 只在编辑模式下设置删除和添加监听
        if (isEditMode) {
            // 设置删除监听
            commonAdapter.setOnRemoveClickListener((position, item) -> {
                removeFromCommonFunction(item);
            });

            // 设置添加监听
            moduleAdapter.setOnAddClickListener((position, item) -> {
                addToCommonFunction(item);
            });
        } else {
            // 在查看模式下，设置点击跳转事件
            moduleAdapter.setOnItemClickListener((position, item) -> {
                // 点击功能项，跳转到对应页面
                // TODO: 根据item的id跳转到对应页面
                String id = item.getId();
                switch (id) {
                    case "1": //收款单
                        startActivity(PaymentReceiptActivity.class);
                        break;
                    case "2": //电汇收款
                        startActivity(TelegraphicTransferActivity.class);
                        break;
                    case "3": //销售订单
                        startActivity(SalesOrderActivity.class);
                        break;
                    case "4": //代支付
                        startActivity(PendingPaymentActivity.class);
                        break;
                    case "5": //促销管理
                        startActivity(PromotionManagementActivity.class);
                        break;
                    case "6": //终端管理
                        startActivity(TerminalManagementActivity.class);
                        break;
                    case "7": //配送商管理
                        startActivity(DeliveryProviderActivity.class);
                        break;
                    case "8": //业务员管理
                        startActivity(SalesPersonActivity.class);
                        break;
                    case "9": //销售线索
                        startActivity(SalesLeadsActivity.class);
                        break;
                    case "10": //打卡管理
                        startActivity(ClockInManageActivity.class);
                        break;
                    case "11": //冰柜管理
                        startActivity(FreezerManagementActivity.class);
                        break;
                    case "12": //账期单
                        startActivity(PaymentTermActivity.class);
                        break;
                    case "13": //金豆管理
                        startActivity(GoldBeanManagementActivity.class);
                        break;
                    case "14": //拜访管理
                        startActivity(VisitManagementActivity.class);
                        break;
                    case "15": //促销拜访
                        startActivity(PromotionVisitActivity.class);
                        break;
                    case "16": //日报管理
                        startActivity(DailyReportActivity.class);
                        break;
                    case "17": //配送管理-经销
                        startActivity(DeliveryManagementTerminalActivity.class);
                        break;
                    case "18": //配送管理-订单
                        startActivity(DeliveryManagementOrderActivity.class);
                        break;
                    case "19": //配送商对账
                        startActivity(DeliveryProviderReconciliationActivity.class);
                        break;
                }
            });
        }
        
        // 在查看模式下，隐藏确认按钮和常用功能区域
        if (MODE_VIEW_ALL.equals(currentMode)) {
            btnConfirm.setVisibility(View.GONE);
            tvCommonHint.setVisibility(View.GONE);
            llCommonFunctionLayout.setVisibility(View.GONE);
            viewDivider.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        // 初始化模拟数据
        initMockData();
        
        // 从Intent中获取已选择的常用功能列表
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra(com.gewu.pm.other.IntentKey.DATA_LIST)) {
            @SuppressWarnings("unchecked")
            List<FunctionItemBean> selectedFunctions = (List<FunctionItemBean>) intent.getSerializableExtra(com.gewu.pm.other.IntentKey.DATA_LIST);
            if (selectedFunctions != null && !selectedFunctions.isEmpty()) {
                // 清空默认的常用功能
                commonFunctionList.clear();
                
                // 添加传递过来的常用功能，并标记为已添加
                for (FunctionItemBean selectedItem : selectedFunctions) {
                    // 在所有功能中查找匹配的项
                    for (FunctionModuleBean module : functionModuleList) {
                        for (FunctionItemBean item : module.getFunctionList()) {
                            if (item.getId().equals(selectedItem.getId())) {
                                item.setAdded(true);
                                commonFunctionList.add(item);
                                break;
                            }
                        }
                    }
                }
                
                // 刷新适配器
                commonAdapter.setData(commonFunctionList);
                moduleAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 初始化模拟数据
     */
    private void initMockData() {
        // 主体功能
        List<FunctionItemBean> mainFunctions = new ArrayList<>();
        FunctionItemBean item1 = new FunctionItemBean("1", "收款单", R.mipmap.label_receipt_ic);
        FunctionItemBean item2 = new FunctionItemBean("2", "电汇收款", R.mipmap.label_remittance_ic);
        FunctionItemBean item3 = new FunctionItemBean("3", "销售订单", R.mipmap.label_sales_order_ic);
        FunctionItemBean item4 = new FunctionItemBean("4", "代支付", R.mipmap.label_payment_behalf_ic);
        FunctionItemBean item5 = new FunctionItemBean("5", "促销管理", R.mipmap.label_promotion_ic);
        mainFunctions.add(item1);
        mainFunctions.add(item2);
        mainFunctions.add(item3);
        mainFunctions.add(item4);
        mainFunctions.add(item5);
        functionModuleList.add(new FunctionModuleBean("主体功能", mainFunctions));

        // 客户管理
        List<FunctionItemBean> customerFunctions = new ArrayList<>();
        customerFunctions.add(new FunctionItemBean("6", "终端管理", R.mipmap.label_terminal_ic));
        customerFunctions.add(new FunctionItemBean("7", "配送商管理", R.mipmap.label_distributor_ic));
        customerFunctions.add(new FunctionItemBean("8", "业务员管理", R.mipmap.label_salesperson_ic));
        customerFunctions.add(new FunctionItemBean("9", "销售线索", R.mipmap.label_sales_leads_ic));
        customerFunctions.add(new FunctionItemBean("10", "打卡管理", R.mipmap.label_attendance_ic));
        functionModuleList.add(new FunctionModuleBean("客户管理", customerFunctions));

        // 资金管理
        List<FunctionItemBean> fundFunctions = new ArrayList<>();
        FunctionItemBean item19 = new FunctionItemBean("19", "配送商对账", R.mipmap.label_delivery_provider_reconciliation_ic);
        FunctionItemBean item11 = new FunctionItemBean("11", "冰柜管理", R.mipmap.label_freezer_ic);
        FunctionItemBean item12 = new FunctionItemBean("12", "账期单", R.mipmap.label_account_period_ic);
        FunctionItemBean item13 = new FunctionItemBean("13", "金豆管理", R.mipmap.label_golden_ic);
        fundFunctions.add(item19);
        fundFunctions.add(item11);
        fundFunctions.add(item12);
        fundFunctions.add(item13);
        functionModuleList.add(new FunctionModuleBean("资金管理", fundFunctions));

        // 外勤管理
        List<FunctionItemBean> fieldFunctions = new ArrayList<>();
        fieldFunctions.add(new FunctionItemBean("14", "拜访管理", R.mipmap.label_visit_ic));
        fieldFunctions.add(new FunctionItemBean("15", "促销拜访", R.mipmap.label_promotion_visit_ic));
        fieldFunctions.add(new FunctionItemBean("16", "日报管理", R.mipmap.label_daily_report_ic));
        functionModuleList.add(new FunctionModuleBean("外勤管理", fieldFunctions));

        // 配送管理
        List<FunctionItemBean> deliveryFunctions = new ArrayList<>();
        FunctionItemBean item17 = new FunctionItemBean("17", "配送管理(经销)", R.mipmap.label_courier_management_terminal_ic);
        FunctionItemBean item18 = new FunctionItemBean("18", "配送管理(订单)", R.mipmap.label_courier_management_order_ic);
        deliveryFunctions.add(item17);
        deliveryFunctions.add(item18);
        functionModuleList.add(new FunctionModuleBean("配送管理", deliveryFunctions));

        // 初始化常用功能（销售订单、冲柜管理、配送管理）
        item3.setAdded(true);
        commonFunctionList.add(item3);
        
        item11.setAdded(true);
        commonFunctionList.add(item11);
        
        item17.setAdded(true);
        commonFunctionList.add(item17);

        // 刷新数据
        moduleAdapter.setData(functionModuleList);
        commonAdapter.setData(commonFunctionList);
    }

    /**
     * 添加到常用功能
     */
    private void addToCommonFunction(FunctionItemBean item) {
        if (commonFunctionList.size() >= MAX_COMMON_FUNCTION_COUNT) {
            toast(getString(R.string.common_function_max_hint, MAX_COMMON_FUNCTION_COUNT));
            return;
        }

        // 检查是否已存在
        for (FunctionItemBean function : commonFunctionList) {
            if (function.getId().equals(item.getId())) {
                toast(R.string.common_function_already_added);
                return;
            }
        }

        // 添加到常用功能
        item.setAdded(true);
        commonFunctionList.add(item);
        commonAdapter.notifyDataSetChanged();

        // 刷新模块列表
        moduleAdapter.notifyDataSetChanged();
    }

    /**
     * 从常用功能中移除
     */
    private void removeFromCommonFunction(FunctionItemBean item) {
        item.setAdded(false);
        commonFunctionList.remove(item);
        commonAdapter.notifyDataSetChanged();

        // 刷新模块列表，让加号重新显示
        moduleAdapter.notifyDataSetChanged();
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_bottom_button) {
            // 打印常用功能列表
            StringBuilder sb = new StringBuilder();
            sb.append("常用功能列表共 ").append(commonFunctionList.size()).append(" 个：\n");
            for (int i = 0; i < commonFunctionList.size(); i++) {
                FunctionItemBean item = commonFunctionList.get(i);
                sb.append((i + 1)).append(". ")
                  .append(item.getName())
                  .append(" (ID: ").append(item.getId()).append(")\n");
            }
            LogUtils.d("CommonFunction", sb.toString());

            // 保存常用功能配置
            // TODO: 这里可以保存到SharedPreferences或数据库

            // 通过EventBus发送更新事件
            EventBusUtil.sendEvent(new EventBean<>(EventCode.COMMON_FUNCTION_UPDATE, new ArrayList<>(commonFunctionList)));
            
            // 返回数据给调用方（兼容startForResult方式）
            Intent resultIntent = new Intent();
            resultIntent.putExtra(com.gewu.pm.other.IntentKey.DATA_LIST, (java.io.Serializable) new ArrayList<>(commonFunctionList));
            setResult(RESULT_OK, resultIntent);
            
            // 返回首页
            finish();
        }
    }
}

